package com.ptszyxx.popose.module.main.dynamic;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.RadioGroup;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;
import androidx.viewpager2.widget.ViewPager2;

import com.ptszyxx.popose.BR;
import com.ptszyxx.popose.R;
import com.ysg.http.data.AppViewModelFactory;
import com.ptszyxx.popose.databinding.FragmentDynamicBinding;
import com.ptszyxx.popose.module.main.dynamic.vm.DynamicVM;
import com.ysg.base.BaseFragment;
import com.ysg.base.FragmentPageAdapter;

import java.util.ArrayList;
import java.util.List;

public class DynamicFragment extends BaseFragment<FragmentDynamicBinding, DynamicVM> {
    public static DynamicFragment getInstance() {
        return new DynamicFragment();
    }

    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_dynamic;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public DynamicVM initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getActivity().getApplication());
        return ViewModelProviders.of(this, factory).get(DynamicVM.class);
    }

    @Override
    public void initView() {
        super.initView();
        binding.rgTab.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
                if (checkedId == R.id.rbFollow) {
                    setTabUI(1);
                }else{
                    setTabUI(0);
                }
            }
        });

        initViewPager();
    }

    private void initViewPager() {
        List<Fragment> fragments = new ArrayList<>();
        fragments.add(new DynamicTabFragment(1));
        fragments.add(new DynamicTabFragment(2));
        binding.viewPager.setOrientation(ViewPager2.ORIENTATION_HORIZONTAL);
        FragmentPageAdapter adapter = new FragmentPageAdapter(getChildFragmentManager(), getLifecycle(), fragments);
        binding.viewPager.setAdapter(adapter);

        binding.viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                switch (position){
                    case 0:
                        binding.rgTab.check(R.id.rbAll);
                        break;
                    case 1:
                        binding.rgTab.check(R.id.rbFollow);
                        break;
                }
            }
        });
    }

    private void setTabUI(int tab) {
        binding.viewPager.setCurrentItem(tab);
    }
}
